<template>
  <el-container style="min-height: 100vh">
    <!-- 侧边栏导航 -->
    <el-aside width="200px" class="sidebar">
      <div class="sidebar-logo">
        <h2>商家管理系统</h2>
      </div>
      <el-menu
        default-active="merchant/dishes"
        class="sidebar-menu"
        router
        :unique-opened="true"
      >
        <!-- 商家管理 -->
        <el-menu-item index="/merchant/manage">
          <span>商家管理</span>
        </el-menu-item>
        <!-- 餐品管理（当前页） -->
        <el-menu-item index="/merchant/dishes">
          <span>餐品管理</span>
        </el-menu-item>
        <!-- 对账申请 -->
        <el-menu-item index="/merchant/reconciliation">
          <span>对账申请</span>
        </el-menu-item>
      </el-menu>
    </el-aside>

    <!-- 主内容区 -->
    <el-container>
      <!-- 顶部导航栏（含退出按钮） -->
      <el-header class="header">
        <div class="header-title">餐品管理</div>
        <el-button 
          type="default" 
          @click="handleLogout"
          class="logout-btn"
        >
          退出登录
        </el-button>
      </el-header>

      <el-main class="main-content">
        <div class="operation-bar">
          <el-button type="primary" @click="handleAdd">新增餐品</el-button>
        </div>
        
        <el-table
          :data="dishes"
          border
          style="width: 100%; margin-top: 20px"
        >
          <el-table-column prop="dishId" label="餐品ID" align="center" width="80" />
          <el-table-column prop="name" label="餐品名称" align="center" />
          <el-table-column prop="price" label="价格" align="center" width="100">
            <template #default="scope">{{ scope.row.price.toFixed(2) }}</template>
          </el-table-column>
          <el-table-column prop="type" label="类型" align="center" />
          <el-table-column prop="sales" label="销量" align="center" width="80" />
          <el-table-column prop="status" label="状态" align="center" width="120">
            <template #default="scope">
              <el-switch
                v-model="scope.row.status"
                :active-value="1"
                :inactive-value="0"
                active-text="在售"
                inactive-text="下架"
                @change="handleStatusChange(scope.row)"
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="180">
            <template #default="scope">
              <el-button type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
              <el-button type="danger" size="small" @click="handleDelete(scope.row.dishId)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <!-- 新增/编辑弹窗 -->
        <el-dialog
          v-model="isDialogOpen"
          :title="form.dishId ? '编辑餐品' : '新增餐品'"
          width="500px"
        >
          <el-form
            ref="formRef"
            :model="form"
            :rules="formRules"
            label-width="100px"
          >
            <el-form-item label="餐品名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入餐品名称" />
            </el-form-item>
            <el-form-item label="价格" prop="price">
              <el-input v-model="form.price" type="number" placeholder="请输入价格" />
            </el-form-item>
            <el-form-item label="类型" prop="type">
              <el-input v-model="form.type" placeholder="请输入餐品类型" />
            </el-form-item>
            <el-form-item label="状态">
              <el-switch
                v-model="form.status"
                :active-value="1"  
                :inactive-value="0" 
                active-text="在售" 
                inactive-text="下架"
              />
            </el-form-item>
          </el-form>
          <template #footer>
            <el-button @click="isDialogOpen = false">取消</el-button>
            <el-button type="primary" @click="handleSubmit">确定</el-button>
          </template>
        </el-dialog>
      </el-main>
    </el-container>
  </el-container>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useRouter } from 'vue-router';
import type { Dish } from '@/types/index';
import type { ElForm } from 'element-plus';

const router = useRouter();

// 本地餐品列表数据
const dishes = ref<Dish[]>([]);
// 对话框状态
const isDialogOpen = ref(false);
// 表单引用
const formRef = ref<InstanceType<typeof ElForm>>();
// 表单数据
const form = reactive<Partial<Dish>>({
  dishId: 0,
  name: '',
  price: 0,
  type: '',
  status: 1 // 1:在售，0:下架
});

// 表单验证规则
const formRules = reactive({
  name: [
    { required: true, trigger: 'blur', message: '请输入餐品名称' }
  ],
  price: [
    { required: true, trigger: 'blur', message: '请输入价格' },
    { type: 'number', min: 0.01, message: '价格必须大于0', trigger: 'blur' }
  ],
  type: [
    { required: true, trigger: 'blur', message: '请输入餐品类型' }
  ]
});

// 页面加载时获取本地餐品数据
onMounted(() => {
  // 模拟本地数据
  dishes.value = [
    { dishId: 1, name: '宫保鸡丁', price: 18.00, type: '热菜', sales: 120, status: 1 },
    { dishId: 2, name: '鱼香肉丝', price: 16.00, type: '热菜', sales: 98, status: 1 },
    { dishId: 3, name: '番茄鸡蛋', price: 12.00, type: '热菜', sales: 156, status: 1 },
    { dishId: 4, name: '凉拌黄瓜', price: 8.00, type: '凉菜', sales: 76, status: 1 },
    { dishId: 5, name: '米饭', price: 2.00, type: '主食', sales: 320, status: 1 },
    { dishId: 6, name: '可乐', price: 3.00, type: '饮料', sales: 189, status: 0 }
  ];
});

// 打开新增对话框
const handleAdd = () => {
  formRef.value?.resetFields();
  Object.assign(form, { dishId: 0, name: '', price: 0, type: '', status: 1 });
  isDialogOpen.value = true;
};

// 打开编辑对话框
const handleEdit = (row: Dish) => {
  Object.assign(form, { ...row });
  isDialogOpen.value = true;
};

// 提交表单（新增/编辑）
const handleSubmit = async () => {
  formRef.value?.validate(async (valid) => {
    if (valid) {
      try {
        if (form.dishId) {
          // 编辑现有餐品
          const index = dishes.value.findIndex(d => d.dishId === form.dishId);
          if (index !== -1) {
            dishes.value[index] = { ...dishes.value[index], ...form } as Dish;
          }
          ElMessage.success('编辑成功');
        } else {
          // 新增餐品
          const newDish = {
            ...form,
            dishId: Math.max(0, ...dishes.value.map(d => d.dishId)) + 1,
            sales: 0
          } as Dish;
          dishes.value.push(newDish);
          ElMessage.success('新增成功');
        }
        
        isDialogOpen.value = false;
      } catch (error) {
        console.error('操作失败:', error);
        ElMessage.error('操作失败');
      }
    }
  });
};

// 改变状态
const handleStatusChange = (row: Dish) => {
  const statusText = row.status === 1 ? '在售' : '下架';
  ElMessage.success(`餐品"${row.name}"已${statusText}`);
};

// 删除餐品
const handleDelete = async (dishId: number) => {
  try {
    await ElMessageBox.confirm('确定要删除该餐品吗？', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    
    dishes.value = dishes.value.filter(d => d.dishId !== dishId);
    ElMessage.success('删除成功');
  } catch (error) {
    // 取消删除不处理
  }
};

// 退出登录
const handleLogout = async () => {
  try {
    await ElMessageBox.confirm('确定要退出登录吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'info'
    });
    localStorage.removeItem('token');
    localStorage.removeItem('user');
    router.push('/login');
    ElMessage.success('退出成功');
  } catch (error) {
    // 取消退出不处理
  }
};
</script>

<style scoped>
/* 侧边栏样式 */
.sidebar {
  background-color: #f5f7fa;
  border-right: 1px solid #e5e7eb;
}
.sidebar-logo {
  padding: 20px;
  text-align: center;
  border-bottom: 1px solid #e5e7eb;
}
.sidebar-logo h2 {
  margin: 0;
  font-size: 18px;
  color: #333;
}
.sidebar-menu {
  margin-top: 10px;
}
.sidebar-menu .el-menu-item.is-active {
  background-color: #e6f7ff;
  color: #1890ff;
}

/* 顶部导航栏样式 */
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
  background-color: #fff;
  border-bottom: 1px solid #e5e7eb;
  height: 60px;
}
.header-title {
  font-size: 18px;
  font-weight: bold;
  color: #333;
}
.logout-btn {
  border-color: #ff4d4f;
  color: #ff4d4f;
}

/* 主内容区样式 */
.main-content {
  padding: 20px;
  background-color: #fff;
}
.operation-bar {
  margin-bottom: 10px;
}
</style>